package com.example.coursedesign.ui.home;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.example.coursedesign.R;

//设置视频全屏播放
public class FullscreenVideoDialog extends AlertDialog {

    private VideoView videoView;
    private ImageView playButton;
    private Uri videoUri;
    private boolean isPlaying = false;

    public FullscreenVideoDialog(@NonNull Context context, String videoPath) {
        super(context);
        this.videoUri = Uri.parse(videoPath);

        // 请求全屏特征
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 设置全屏标志
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // 加载布局
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_fullscreen_video, null);
        setContentView(view);

        // 初始化视图
        videoView = view.findViewById(R.id.fullscreenVideoView);
        playButton = view.findViewById(R.id.fullscreenPlayButton);

        // 设置视频 URI
        videoView.setVideoURI(videoUri);
        videoView.setOnPreparedListener(mp -> mp.setLooping(true));
        videoView.setOnCompletionListener(mp -> resetVideoViewState());

        // 设置播放按钮点击事件
        playButton.setOnClickListener(v -> toggleVideoPlayback());

        // 设置视频视图点击事件
        videoView.setOnClickListener(v -> toggleVideoPlayback());
    }

    private void toggleVideoPlayback() {
        if (isPlaying) {
            videoView.pause();
            playButton.setImageResource(R.drawable.ic_play); // 设置为播放图标
        } else {
            videoView.start();
            playButton.setImageResource(R.drawable.ic_play); // 设置为暂停图标
        }
        isPlaying = !isPlaying;
    }

    private void resetVideoViewState() {
        videoView.pause();
        playButton.setImageResource(R.drawable.ic_play); // 重新设置为播放按钮
        isPlaying = false;
    }

    @Override
    public void onBackPressed() {
        if (isShowing()) {
            dismiss();
        }
    }
}